﻿#include <stdio.h>

int classwise(unsigned char* ip) {
    unsigned char first = ip[0];
    if (first <= 127)       return 0; // A类
    else if (first <= 191) return 1; // B类
    else if (first <= 223) return 2; // C类
    else if (first <= 239) return 3; // D类
    else                   return 4; // E类
}

typedef struct {
    unsigned char ip[4];
    int expected;
} TestCase;

void print_ip(unsigned char* ip) {
    printf("%3d.%-3d.%-3d.%-3d", ip[0], ip[1], ip[2], ip[3]);
}

void run_tests() {
    int total = 0, pass = 0, fail = 0;

    TestCase test_cases[] = {
        // A类测试
        {{0,   0,   0,   0}, 0},
        {{127, 255, 255, 255}, 0},
        {{64,  128, 200, 1}, 0},

        // B类测试
        {{128, 0,   0,   0}, 1},
        {{191, 255, 255, 255}, 1},
        {{172, 16,  0,   1}, 1},

        // C类测试
        {{192, 0,   0,   0}, 2},
        {{223, 255, 255, 255}, 2},
        {{200, 100, 50,  25}, 2},

        // D类测试
        {{224, 0,   0,   0}, 3},
        {{239, 255, 255, 255}, 3},
        {{230, 128, 64,  32}, 3},

        // E类测试
        {{240, 0,   0,   0}, 4},
        {{255, 255, 255, 255}, 4},
        {{248, 192, 128, 64}, 4},
    };

    int num_cases = sizeof(test_cases) / sizeof(test_cases[0]);

    for (int i = 0; i < num_cases; i++) {
        TestCase tc = test_cases[i];
        int result = classwise(tc.ip);

        printf("测试 %2d: IP=", i + 1);
        print_ip(tc.ip);
        printf(" 预期=%-2d 实际=%-2d ", tc.expected, result);

        if (result == tc.expected) {
            printf("\033[32m✓\033[0m\n");
            pass++;
        }
        else {
            printf("\033[31m✗\033[0m\n");
            fail++;
        }
        total++;
    }

    printf("\n测试结果：\n");
    printf("总用例: %d\n", total);
    printf("\033[32m通过: %d\033[0m\n", pass);
    printf("\033[31m失败: %d\033[0m\n", fail);
}

int main() {
    printf("=== IP地址分类测试 ===\n");
    run_tests();
    return 0;
}